package com.bw.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.app.func.TableProcessFunction;
import com.bw.gmall.realtime.bean.TableProcess;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import com.bw.gmall.realtime.utils.MysqlUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

public class DimApp {
    public static void main(String[] args) throws Exception {
        //todo 1.获取环境变量
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //todo 2.设置并行度 (重)
        env.setParallelism(1);

        //todo 3.读取topic_db主流数据
        String topic="topic_db";
        //组分区 并行消费
        //不重复消费，没有组会重复消费
        String groupId="dimapp";

        // 消费
        System.out.println("Kafka 消费者已创建，准备接收数据");
        DataStreamSource<String> ds = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));
        //ds.print("接收到 Kafka 数据：");

        //todo 3.过滤非json数据 保留新增及变化及初始化数据
        SingleOutputStreamOperator<JSONObject> filterJSONDS = ds.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    String type = jsonObject.getString("type");
                    if (type.equals("insert") || type.equals("update") || type.equals("bootstrap-insert")) {
                        out.collect(jsonObject);
                    }

                } catch (Exception e) {
                    System.out.println("错误数据不是json数据" + value);
                }
            }
        });

        // TODO: 4.使用flinck 读取mysql 配置信息表 创建配置流

        DataStream<String> mysqlDs = MysqlUtil.cdcMysql(env, "gmall_config", "table_process");

        mysqlDs.print("FlinkCDC:");


        //todo: 5. 将配置流处理为广播流
        MapStateDescriptor<String, TableProcess> mapState = new MapStateDescriptor<>("mapState", String.class, TableProcess.class);

        BroadcastStream<String> broadcastStream = mysqlDs.broadcast(mapState);
        //主流和广播流进行关联
        //todo 6:连接主流和广播流
        BroadcastConnectedStream<JSONObject, String> connect = filterJSONDS.connect(broadcastStream);

        //todo 7:处理连接流 根据配置信息处理主流数据 （将配置信息存入到状态中 主流读状态）
        SingleOutputStreamOperator<JSONObject> process = connect.process(new TableProcessFunction());
        // 启动任务
        env.execute();
    }
}
